package com.taiji.tvlauncher;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.util.Enumeration;

import android.app.Activity;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;


public class SystemInfo
{
    private static final String TAG = "SystemInfo";

    public static String getMainInfo(Activity activity)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("本机IP地址：");
        sb.append(getLocalIPAddr());
        sb.append("\r\n");
        sb.append("有线网卡：");
        sb.append(getEthMacAddress());
        sb.append("\r\n");
        sb.append("无线网卡：");
        sb.append(getWifiMacAddress());
        sb.append("\r\n");
        sb.append(getDisplayMetricsInfo(activity));

        return sb.toString();
    }

    public static String getAllInfo(Activity activity)
    {
        StringBuilder sb = new StringBuilder();
        sb.append(getMainInfo(activity));
        sb.append(getPlatformInfo());
        return sb.toString();
    }

    public static String getDisplayMetricsInfo(Activity activity)
    {
        if(activity == null)
        {
            throw new IllegalArgumentException("getDisplayMetricsInfo activity is null");
        }
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        StringBuilder sb = new StringBuilder();
        sb.append("\r\n[主机屏幕参数]\r\n");
        sb.append("DisplayMetrics density = " + dm.density + "\r\n");
        sb.append("DisplayMetrics densityDpi = " + dm.densityDpi + "\r\n");
        sb.append("DisplayMetrics scaledDensity = " + dm.scaledDensity + "\r\n");
        sb.append("DisplayMetrics widthPixels = " + dm.widthPixels + "\r\n");
        sb.append("DisplayMetrics heightPixels = " + dm.heightPixels + "\r\n");
        sb.append("DisplayMetrics xdpi = " + dm.xdpi + "\r\n");
        sb.append("DisplayMetrics ydpi = " + dm.ydpi + "\r\n");
        return sb.toString();
    }

    public static  String getEthMacAddress() {
        String macSerial = null;
        String str = "";
        boolean ethflag = isFileExists("/sys/class/net/eth0/address");
        if (ethflag == true) {
            try {
                Process pp = Runtime.getRuntime().exec("cat /sys/class/net/eth0/address");
                InputStreamReader ir = new InputStreamReader(pp.getInputStream(), Charset.defaultCharset());
                LineNumberReader input = new LineNumberReader(ir);
                while (null != str) {
                    str = input.readLine();
                    if (str != null) {
                        macSerial = str.trim();
                        break;
                    }
                }
            } catch (IOException ex) {
                LogUtil.error(TAG, "getWifiMacAddress IOException:" + ex.getMessage());
            }
        }
        LogUtil.debug(TAG, "getEthMacAddress Address=" + macSerial);
        return macSerial;
    }

    public static  String getWifiMacAddress() {
        String macSerial = null;
        String str = "";
        boolean wlanflag = isFileExists("/sys/class/net/wlan0/address");
        if (wlanflag == true) {
            try {
                Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
                InputStreamReader ir = new InputStreamReader(pp.getInputStream(), Charset.defaultCharset());
                LineNumberReader input = new LineNumberReader(ir);
                while (null != str) {
                    str = input.readLine();
                    if (str != null) {
                        macSerial = str.trim();
                        break;
                    }
                }
            } catch (IOException ex) {
                LogUtil.error(TAG, "getWifiMacAddress IOException:" + ex.getMessage());
            }
        }
        LogUtil.debug(TAG, "getWifiMacAddress Address=" + macSerial);
        return macSerial;
    }


    public static  boolean isFileExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static String getLocalIPAddr()
    {
        String ipaddress = "[无法获取本机有线网络IP地址]";
        try
        {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements())
            {
                NetworkInterface intf = en.nextElement();
                if (intf.getName().toLowerCase().equals("eth0") || intf.getName().toLowerCase().equals("wlan0"))
                {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
                    {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress())
                        {
                            Log.d(TAG, "getEthernetIPAddr ip.getHostAddress()" + inetAddress.getHostAddress());
                            ipaddress = inetAddress.getHostAddress().toString();
                            if (!ipaddress.contains("::"))//::是ipV6的地址
                            {
                                Log.d(TAG, ipaddress);
                                return ipaddress;
                            }
                        }
                    }
                }
                else
                {
                    continue;
                }
            }
        }
        catch (SocketException e)
        {
            Log.e(TAG, "获取本地有线网络IP地址失败");
            e.printStackTrace();
        }
        Log.d(TAG, ipaddress);
        return ipaddress;
    }

    /**
     * 获取平台信息
     */
    private static String getPlatformInfo()
    {
        StringBuilder sb = new StringBuilder();
        sb.append("\r\n[主机设备参数]\r\n");
        // sb.append("Product Model = " + android.os.Build.MODEL + "\r\n");
        sb.append("Android SDK = " + android.os.Build.VERSION.SDK_INT + "\r\n");
        sb.append("Android RELEASE = " + android.os.Build.VERSION.RELEASE + "\r\n");
        try
        {
            Field[] fields = Build.class.getFields();
            for (Field field : fields)
            {
                field.setAccessible(true); // 暴力反射
                String key = field.getName();
                Object value = field.get(null);

                if(value instanceof String)
                {
                    sb.append(key + " = " + value + "\r\n");
                }
                if(value instanceof String[])
                {
                    String newStr = ((String[])value).toString();
                    sb.append(key + " = " + newStr + "\r\n");
                }
            }
        }
        catch (IllegalArgumentException e)
        {
            e.printStackTrace();
        }
        catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }
        return sb.toString();
    }
}